package fueltrack.server;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;

import fueltrack.server.motormouth.Credentials;
import fueltrack.server.motormouth.HTMLParser;
import fueltrack.server.motormouth.MotorMouthService;
import fueltrack.server.motormouth.model.FuelPriceRecord;


public class RetrieveFuelPriceDataServlet extends HttpServlet {

	private static final long serialVersionUID = -2486079003679793041L;

	private DatastoreService datastoreService;

	public RetrieveFuelPriceDataServlet() {
		super();
		
		datastoreService = DatastoreServiceFactory.getDatastoreService();
	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//		System.out.println("Executing MotorMouth scrape...");
		
		try {
			InputStream htmlInputStream = MotorMouthService.retrievePricesHTML(Credentials.MOTOR_MOUTH_USERNAME, Credentials.MOTOR_MOUTH_PASSWORD);
			
			List<FuelPriceRecord> records = HTMLParser.parseHTML(new InputStreamReader(htmlInputStream));
//			List<FuelPriceRecord> records = HTMLParser.parseHTML(new StringReader(html));
//			List<FuelPriceRecord> records = HTMLParser.parseHTML(new FileReader("input.txt"));
			
			for (FuelPriceRecord record : records) {
				addFuelPriceRecord(record);
				resp.getWriter().append(record.toString()).append("\r\n");
			}
			
//			resp.getWriter().append("Success");
		} catch (Exception e) {
			throw new ServletException(e);
//			resp.getWriter().append("Exception occured");
//			e.printStackTrace();
		}
	}

	private void addFuelPriceRecord(FuelPriceRecord record) {
		Entity entity = new Entity(FuelPriceRecord.class.getSimpleName());
		
		entity.setProperty("name", record.getName());
		entity.setProperty("address", record.getAddress());
		entity.setProperty("postCode", record.getPostCode());
		entity.setProperty("suburb", record.getSuburb());
		entity.setProperty("collectedDate", record.getCollectedDate());
		entity.setProperty("decicents", record.getDecicents());
		entity.setProperty("retrievedDate", new Date());
		
		datastoreService.put(entity);
	}

}
